<template>

  <div class="wrap">
    <TopNav>
      <template #left>
        <div class="device_info">
          <MinWindow />
          <span style="margin-right:10px">版本号: v{{ version }}</span>
          <span class="number" @click="handleCopy">设备号: {{ uuid }} <el-icon :size="20" style="margin-left: 5px;">
              <DocumentCopy />
            </el-icon></span>
          <div class="shop" style="margin-left: 15px;">{{ userStore.shopInfo.shopName }}</div>
        </div>
      </template>
      <template #right>

        <!-- <el-button type="danger" @click="closeWindow" circle size="large"> <SvgIcon name="close" color="#fff" size="24" /></el-button> -->
        <CloseApp />
      </template>


    </TopNav>

    <div class="login_wrap">
      <div class="top">
        <img src="../assets/logo.png" style="width: 150px;margin-right: 10px;"></img>
        <div class="title">一手店销售系统</div>
      </div>
      <el-form :size="formSize" hide-required-asterisk ref="ruleFormRef" style="max-width: 600px" :model="ruleForm"
        :rules="rules" label-width="auto" class="demo-ruleForm">
        <el-form-item label="" prop="account">

          <el-input :prefix-icon="User" autofocus ref="inputRef" placeholder="请输入手机号" @focus="handlePhoneFocus"
            v-model="ruleForm.account" maxlength="11" clearable autocomplete="off" />

        </el-form-item>
        <el-form-item label="" prop="password">
          <el-input :prefix-icon="Lock" placeholder="请输入密码" type="password" @focus="handlePasswordFocus"
            v-model="ruleForm.password" clearable />
        </el-form-item>
        <el-form-item style="flex-wrap: nowrap;">
          <div class="btn_wrap">
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              登录
            </el-button>

          </div>
        </el-form-item>
      </el-form>

    </div>
    <SimpleKeyboard ref="simpleKeyboard" :input="isAccount ? ruleForm.account : ruleForm.password"
      @onChange="onKeyboardChange" @onKeyPress="onKeyPress"></SimpleKeyboard>
  </div>


</template>
<script setup lang='ts'>
// @ts-nocheck
import packageConfig from '../../../../package.json'
import CloseApp from '../components/CloseApp.vue'
import MinWindow from '../components/MinWindow.vue'
import { User, Lock, DocumentCopy } from '@element-plus/icons-vue'

import { useRouter } from 'vue-router';
import { ref, reactive } from 'vue'
import { ElMessage, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
import SimpleKeyboard from '@renderer/components/SimpleKeyboard.vue'
import { useUserStore } from '@renderer/store/user';
import { getShop } from '@renderer/api/login/index'
import { onMounted } from 'vue';

//版本号
const version = packageConfig.version

//获取设备id
let uuid = ref('')

let shopID = ref('')
const userStore = useUserStore()
onMounted(async () => {
  //登录页 删除token
  localStorage.setItem('token', '')
  try {
    uuid.value = await window.electron.ipcRenderer.invoke('getUUID')
    getShopInfo()
  } catch (error) {
    console.log(error)
  }

  ruleForm.account = userStore.account
})


async function getShopInfo() {
  try {
    const { data } = await getShop(uuid.value)
    if (data) {
      shopID.value = data.shopID
      userStore.setShopID(data.shopID)
      userStore.setShopInfo(data)
    } else {
      shopID.value = ''
      userStore.setShopID('')
      userStore.setShopInfo('')
    }

  } catch (error) {
    console.log(error)
  }

}


interface RuleForm {
  account: string
  password: string
}
const formSize = ref<ComponentSize>('large')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  account: '',
  password: ''
})


const rules = reactive<FormRules<RuleForm>>({
  account: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    { min: 11, max: 11, message: '请输入11位手机号', trigger: 'blur' }
  ]
})
const router = useRouter() //获得路由器

async function toLogin() {

  const terminalType = 'SCS'
  const reqData = { ...ruleForm, terminalType, shopID: shopID.value }
  try {
   
    await userStore.toLogin(reqData)
    if(reqData.password==='123456'){
      router.replace('/changepwd')
    }else{
      router.push('/index')
    }
   
  } catch (error) {
    console.log(error)
  }


}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      //console.log('submit!')
    //   if (!/(?=.*\d)(?=.*[a-zA-Z]).{6,20}/.test(ruleForm.password)) {
      
    //   return false
    // }
      await getShopInfo()
      toLogin()
    } else {
      formEl.validateField('account') //只在提交时校验
      formEl.validateField('password')
      console.log('error submit!', fields)
    }
  })
}

const inputRef = ref()
const isAccount = ref(true)
//输入手机号
const handlePhoneFocus = () => {
  isAccount.value = true
}
const handlePasswordFocus = () => {
  isAccount.value = false
}

let simpleKeyboard = ref()
function onKeyboardChange(input) {

  if (isAccount.value) {
    if (input.length > 11) {
      let sliceVal = input.slice(0, 11)
      simpleKeyboard.value.resetKeyboardVal(sliceVal) //子组件也要清空val值
      ruleForm.account = sliceVal
    } else {
      ruleForm.account = input
    }


  } else {
    ruleForm.password = input
  }
}
function onKeyPress(button) {
  if (button === '{enter}') {
    submitForm(ruleFormRef.value)
  }
}

//复制设备号
function handleCopy() {
  navigator.clipboard.writeText(uuid.value).then(function () {

    ElMessage({
      message: '设备号已成功复制到剪贴板',
      type: 'success'
    })
  }, function (err) {
    ElMessage({
      message: '未能复制文本',
      type: 'error'
    })

  });
}


</script>
<style scoped lang='scss'>
.wrap {

  background: var(--color-background);
  background-image: url('../assets/wavy-lines.svg');
  background-size: cover;
  height: 100%;
  box-sizing: border-box;
  position: relative;

  .device_info {
    display: flex;
    align-items: center;
    font-size: 16px;

    .number {
      display: flex;
      align-items: center;
    }
  }

  .close {
    cursor: pointer;
  }
}

.login_wrap {
  position: relative;
  z-index: 11; //这里设置z-index为11 避免被弹出的键盘覆盖住
  width: 400px;
  margin: calc((100vh - 50px - 205px - 300px)/2) auto;
  padding: 20px;
  background-color: #dce9f1;
  box-shadow: 1px 1px 1px 10px rgba(156, 160, 153, 0.3);
  border-radius: 10px;

  .top {
    display: flex;
    align-items: center;
    justify-content: center;

    .title {
      color: #222;
      text-align: center;
      padding: 20px 0;
      font-size: 26px;
      letter-spacing: 2px
    }
  }


  :deep(.el-form-item__label) {
    color: #fff;
  }

  .btn_wrap {
    display: flex;
    align-items: center;
    width: 100%;

    button {
      width: 100%;
    }
  }
}
</style>
